package controllers

import (
	"git.oschina.net/fanbuchi/timemaker/models"
	"git.oschina.net/fanbuchi/timemaker/valid"
	"github.com/astaxie/beego"
	"time"
)

type TaskController struct {
	beego.Controller
}

func (this *TaskController) Get() {
	objectStatus := models.ObjectStatus{Status: models.Ok, Desc: "task error http://api.baidu.com "}
	this.Data[dataformat] = objectStatus
	this.ServeJson()
}

func (this *TaskController) PublicTask() {
	content := this.GetString("content")
	taskType := this.GetString("taskType")
	status, err := this.GetInt16("status", -1)
	exceTaskTime, err := this.GetInt64("exceTaskTime", -1) //立即执行

	if err != nil || status <= -1 {
		status := models.ObjectStatus{Status: models.ParamError, Desc: "param status must int ( 0 1 2 )"}
		this.Data[dataformat] = status
		this.ServeJson()
		this.StopRun()
	}
	exec := time.Unix(exceTaskTime, 0)

	if err != nil || exec.Add(1*60*60*1000).After(time.Now()) {
		status := models.ObjectStatus{Status: models.ParamError, Desc: "param exceTaskTime  must be time"}
		this.Data[dataformat] = status
		this.ServeJson()
		this.StopRun()
	}
	validationResult := valid.ValidCreateTask(content, taskType, exec)
	if !validationResult.Ok {
		status := models.ObjectStatus{Status: models.ParamError, Desc: validationResult.Error.Key + " " + validationResult.Error.Message}
		this.Data[dataformat] = status
		this.ServeJson()
	} else {
		profile, err := models.CreateTask("userid_111111", content, taskType, exec, status)
		if err != nil {
			this.Data[dataformat] = profile
		} else {
			this.Data[dataformat] = profile
		}
		this.ServeJson()
	}

}
func (this *TaskController) DelTask() {
	taskId := this.GetString("taskId")
	_, err := models.DelTask(taskId)
	if err != nil {
		status := models.ObjectStatus{Status: models.ParamError, Desc: err.Error()}
		this.Data[dataformat] = status
	} else {
		status := models.ObjectStatus{Status: models.Ok, Desc: "ok"}
		this.Data[dataformat] = status
	}
	this.ServeJson()
}

func (this *TaskController) ProtectedTask() {
	taskId := this.GetString("taskId")
	_, err := models.UpdateTaskStatus(taskId, 0)
	if err != nil {
		status := models.ObjectStatus{Status: models.ParamError, Desc: err.Error()}
		this.Data[dataformat] = status
	} else {
		status := models.ObjectStatus{Status: models.Ok, Desc: "ok"}
		this.Data[dataformat] = status
	}
	this.ServeJson()
}

func (this *TaskController) GetTmpTasksById() {

}

func (this *TaskController) GetTmpTasksByPage() {

}

func (this *TaskController) EditTmpTask() {

}

func (this *TaskController) GetTaskById() {

}

func (this *TaskController) GetTasksByPage() {

}

func (this *TaskController) GetTasksByTag() {

}
